#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

typedef struct edge{
	int adjvex;
	struct edge *next;
}edge;

typedef struct vnode{ 
	int id;//in degree
	edge *link; 
}vnode,Adjlist[100]; 

typedef Adjlist LGraph; 
typedef struct snode{ 
	int data; 
	struct snode *next; 
}Link_Stack; 

Link_Stack *top,*s; 

void dfs_visit(LGraph gl, int v)
{
	gl[v].id = 1;
	//each vertex from v
	edge * e = gl[v].link;
	while(e){
		if(gl[e->adjvex].id == 0){
			dfs_visit(gl, e->adjvex);
		}
		e = e->next;
	}
	printf("%d\n", v);
	gl[v].id = 2;
}

void dfs(LGraph gl, int n)
{
	int i;
	for(i=0;i<n;i++)
		if(gl[i].id == 0)
			dfs_visit(gl, i);
}

void Push(Link_Stack **top,int x)
{ 
	s=(Link_Stack*)malloc(sizeof(Link_Stack)); 
	s->data=x; 
	s->next=(*top)->next; 
	(*top)->next=s;
}

void GetTop(Link_Stack **top,int *x)
{ 
	s=(*top)->next; 
	*x=s->data; 
	(*top)->next=s->next; 
	free(s);
}

#define VNUM	3
#define ENUM	3
static int edges[ENUM][2] = {{0,1}, {0,2}, {2,1}};

int CreatGraph(LGraph gl)
{ 
	int m,n,i=0,c,d; 
	edge *p; 
	for(i=0;i<VNUM;i++){
		gl[i].link=NULL; 
		gl[i].id=0;
	}
	for(i=0;i<ENUM;i++){
		m = edges[i][0];
		n = edges[i][1];
		printf("scanf %d -> %d\n", m, n);
		if((m>=0)&&(m<VNUM)&&(n>=0)&&(n<VNUM)){
			p=(edge*)malloc(sizeof(edge));
			p->adjvex=n;
			p->next=gl[m].link;
			gl[m].link=p;
			gl[n].id++;
		}
	}
	return VNUM;
}

void TopuSort(LGraph G,int n)
{
	int i,j,m=0;
	edge *p;
	top=(Link_Stack*)malloc(sizeof(Link_Stack));
	top->next=NULL;
	for(i=0;i<n;i++)
		if(G[i].id==0) Push(&top,i);
	while(top->next!=NULL){
		GetTop(&top,&i);
		printf(" %d ",i);
		m++;
		p=G[i].link;
		while(p){
			j=p->adjvex;
			G[j].id--;
			if(G[j].id==0) Push(&top,j);
			p=p->next;
		}
	}
	if(m<n) printf("The Graph has a cycle!\n");
	else	printf("\n");
}

int main()
{
	LGraph GL;
	CreatGraph(GL);
	TopuSort(GL, VNUM);
	dfs(GL, VNUM);
	return 0;
}
